package com.cxyzy.timerdemo

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.concurrent.fixedRateTimer

class MainActivity : AppCompatActivity() {
    lateinit var timer: Timer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        startBtn.setOnClickListener { startTimer() }
        stopBtn.setOnClickListener { stopTimer() }
    }

    private fun startTimer() {
        timer = fixedRateTimer("", false, 0, 1000) {
            toast("得瑟中。。。")
            Log.d("MainActivity", "得瑟中。。。")
        }
    }

    private fun stopTimer() {
        timer.cancel()
        toast("醒醒！！！")
        Log.d("MainActivity", "醒醒！！！")
    }

    private fun toast(text: String) {
        runOnUiThread {
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
        }
    }
}